/**
 * Notes: 全局或者主页模块控制器 
 * Date: 2020-11-05 10:20:00 
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 */

const BaseProjectController = require('./base_project_controller.js');
const HomeService = require('../service/home_service.js');
const cloudBase = require('../../../framework/cloud/cloud_base.js');
const timeUtil = require('../../../framework/helpers/time_util.js');
const dataUtil = require('../../../framework/helpers/data_util.js');
const dbUtil = require('../../../framework/database/db_util.js');
const UserModel = require('../model/user_model.js');

class HomeController extends BaseProjectController {

	async getSetup() {
		// 数据校验
		let rules = {
			key: 'must|string|name=KEY',
		};

		// 取得数据
		let input = this.validateData(rules);

		return await HomeService.getSetup(input.key);
	}

	/** 首页推荐列表 */
	async getHomeList() {
		let service = new HomeService();
		return await service.getHomeList(this._userId);
	}

	async workData() {
		try {
			// 确保数据库已初始化
			await this.initSetup();

			// 获取用户ID
			let userId = this._userId;
			if (!userId) return this.createError('用户未登录');

			console.log('[工作台API] 获取用户工作数据, 用户ID:', userId);

			// 获取用户信息
			let user = null;
			try {
				const db = cloudBase.getCloud().database();
				const result = await db.collection('oa_user')
					.where({ USER_MINI_OPENID: userId, USER_STATUS: 1 })
					.get();
				if (result.data && result.data.length > 0) {
					user = result.data[0];
				}
			} catch (err) {
				console.error('获取用户信息失败:', err);
			}
			
			if (!user) {
				console.warn('[工作台API] 未找到用户信息');
				return this.createError('未找到用户信息');
			}

			console.log('[工作台API] 用户信息:', {
				id: user._id,
				dept: user.USER_DEPT,
				auth: user.USER_AUTH
			});

			const db = cloudBase.getCloud().database();
			const _ = db.command;

			// 获取待办事项数量 - 我发起的且状态为待审批的
			let todoCount = 0;
			try {
				const result = await db.collection('oa_flow')
					.where({
						FLOW_STATUS: _.in([0, 1]), // 待处理的状态
						FLOW_USER_ID: userId
					})
					.count();
				todoCount = result.total || 0;
				console.log('[工作台API] 我发起的待审批数量:', todoCount);
			} catch (err) {
				console.error('获取待办事项数量失败:', err);
			}

			// 获取待我审批数量 - 只有管理员可以审批
			let approvalPendingCount = 0;
			if (user.USER_AUTH == 1) {
				try {
					const result = await db.collection('oa_flow')
						.where({
							FLOW_STATUS: 1, // 审批中状态
							FLOW_TO_DEPT: user.USER_DEPT
						})
						.count();
					approvalPendingCount = result.total || 0;
					console.log('[工作台API] 待我审批数量:', approvalPendingCount);
				} catch (err) {
					console.error('获取待我审批数量失败:', err);
				}
			}

			// 获取已办事项数量
			let doneCount = 0;
			try {
				const result = await db.collection('oa_flow')
					.where({
						FLOW_STATUS: _.in([2, 3, 9]), // 已完成的状态
						FLOW_USER_ID: userId
					})
					.count();
				doneCount = result.total || 0;
				console.log('[工作台API] 已完成的审批数量:', doneCount);
			} catch (err) {
				console.error('获取已办事项数量失败:', err);
			}

			// 获取进行中的项目数量
			let projectCount = 0;
			try {
				const result = await db.collection('oa_project')
					.where({
						STATUS: 1, // 进行中状态
						USER_ID: userId
					})
					.count();
				projectCount = result.total || 0;
				console.log('[工作台API] 进行中的项目数量:', projectCount);
			} catch (err) {
				console.error('获取项目数量失败:', err);
			}

			// 获取待完成任务数量
			let taskCount = 0;
			try {
				const result = await db.collection('oa_task')
					.where({
						STATUS: 0, // 未完成状态
						USER_ID: userId
					})
					.count();
				taskCount = result.total || 0;
				console.log('[工作台API] 待完成任务数量:', taskCount);
			} catch (err) {
				console.error('获取待完成任务数量失败:', err);
			}

			// 获取正在处理的任务数量
			let taskDoingCount = 0;
			try {
				const result = await db.collection('oa_task')
					.where({
						STATUS: 1, // 处理中状态
						USER_ID: userId
					})
					.count();
				taskDoingCount = result.total || 0;
				console.log('[工作台API] 正在处理的任务数量:', taskDoingCount);
			} catch (err) {
				console.error('获取处理中任务数量失败:', err);
			}

			// 准备返回数据
			const result = {
				todoCount: todoCount || 0,
				doneCount: doneCount || 0,
				approvalPendingCount: approvalPendingCount || 0,
				projectCount: projectCount || 0,
				taskCount: taskCount || 0,
				taskDoingCount: taskDoingCount || 0,
				
				// 直接添加前端期望的字段映射
				approvalTotal: (todoCount || 0) + (doneCount || 0),
				taskTotal: taskCount || 0,
				taskDoing: taskDoingCount || 0,
				projectTotal: projectCount || 0
			};

			console.log('[工作台API] 返回数据:', result);
			return this.createSuccess(result);

		} catch (err) {
			console.error('[工作台API] 获取工作数据失败：', err);
			return this.createError('获取工作数据失败: ' + err.message);
		}
	}

	async dynamicList() {
		try {
			// 确保数据库已初始化
			await this.initSetup();

			// 获取用户ID
			let userId = this._userId;
			if (!userId) return this.createError('用户未登录');

			// 获取最近的动态信息
			let list = [];
			try {
				const db = cloudBase.getCloud().database();
				const collection = db.collection('oa_dynamic');
				const result = await collection
					.where({ USER_ID: userId })
					.orderBy('ADD_TIME', 'desc')
					.limit(10)
					.get();
				list = result.data || [];
			} catch (err) {
				console.error('查询动态信息失败：', err);
			}

			// 处理每条动态的数据
			list = list.map(item => ({
				_id: item._id,
				avatar: item.AVATAR || '/projects/oa/images/tabbar/home.png',
				name: item.NAME || '未知用户',
				time: timeUtil.timestamp2Time(item.ADD_TIME) || '未知时间',
				content: item.CONTENT || '',
				type: item.TYPE || '',
				typeText: this._getTypeText(item.TYPE)
			}));

			// 获取知识库相关动态
			let knowledgeDynamics = [];
			try {
				const db = cloudBase.getCloud().database();
				const collection = db.collection('oa_knowledge');
				const result = await collection
					.where({ KNOWLEDGE_STATUS: db.command.in([2, 3]) })
					.orderBy('KNOWLEDGE_ADD_TIME', 'desc')
					.limit(5)
					.get();
				knowledgeDynamics = result.data || [];
			} catch (err) {
				console.error('查询知识库动态失败：', err);
			}

			// 处理知识库动态数据
			knowledgeDynamics = knowledgeDynamics.map(item => ({
				_id: item._id,
				avatar: '/projects/oa/images/tabbar/knowledge.png',
				name: '知识库',
				time: timeUtil.timestamp2Time(item.KNOWLEDGE_ADD_TIME) || '未知时间',
				content: `${item.KNOWLEDGE_TITLE}`,
				type: 'knowledge',
				typeText: '知识库',
				path: `../../knowledge/detail/knowledge_detail?id=${item._id}`
			}));

			// 合并所有动态
			list = [...list, ...knowledgeDynamics];

			// 按时间倒序排序
			list.sort((a, b) => {
				const timeA = new Date(a.time || Date.now()).getTime();
				const timeB = new Date(b.time || Date.now()).getTime();
				return timeB - timeA;
			});

			return this.createSuccess({
				list: list,
				total: list.length
			});

		} catch (err) {
			console.error('获取动态列表失败：', err);
			return this.createSuccess({
				list: [],
				total: 0
			});
		}
	}

	async statistics() {
		try {
			// 确保数据库已初始化
			await this.initSetup();

			// 获取用户ID
			let userId = this._userId;
			if (!userId) return this.createError('用户未登录');

			// 初始化返回数据
			let data = {
				projectProgress: 0,
				taskCompletion: 0,
				approvalEfficiency: 0,
				teamPerformance: 0
			};

			const db = cloudBase.getCloud().database();
			
			// 获取项目数据
			let projects = [];
			try {
				const result = await db.collection('oa_project')
					.where({ USER_ID: userId })
					.get();
				projects = result.data || [];
			} catch (err) {
				console.error('获取项目数据失败:', err);
			}
			
			const completedProjects = projects.filter(p => p.STATUS === 2).length;
			data.projectProgress = projects.length ? Math.round((completedProjects / projects.length) * 100) : 0;

			// 获取任务数据
			let tasks = [];
			try {
				const result = await db.collection('oa_task')
					.where({ USER_ID: userId })
					.get();
				tasks = result.data || [];
			} catch (err) {
				console.error('获取任务数据失败:', err);
			}
			
			const completedTasks = tasks.filter(t => t.STATUS === 1).length;
			data.taskCompletion = tasks.length ? Math.round((completedTasks / tasks.length) * 100) : 0;

			// 获取审批数据
			const now = Math.floor(Date.now() / 1000); // 获取当前时间戳（秒）
			const lastWeek = now - (7 * 24 * 60 * 60); // 一周前的时间戳
			
			let approvals = [];
			try {
				const result = await db.collection('oa_flow')
					.where({
						USER_ID: userId,
						ADD_TIME: db.command.gte(lastWeek)
					})
					.get();
				approvals = result.data || [];
			} catch (err) {
				console.error('获取审批数据失败:', err);
			}

			// 计算审批效率
			if (approvals.length > 0) {
				let totalTime = 0;
				let count = 0;
				
				approvals.forEach(approval => {
					if (approval.END_TIME) {
						totalTime += (approval.END_TIME - approval.ADD_TIME);
						count++;
					}
				});

				const avgHours = count ? (totalTime / count) / 3600 : 24;
				data.approvalEfficiency = Math.min(100, Math.round((24 / avgHours) * 100));
			}

			// 计算团队绩效
			data.teamPerformance = Math.round(
				(data.projectProgress + data.taskCompletion + data.approvalEfficiency) / 3
			);

			console.log('统计数据计算完成:', data);
			
			return this.createSuccess(data);

		} catch (err) {
			console.error('统计数据计算失败:', err);
			return this.createError('获取统计数据失败：' + err.message);
		}
	}

	// 获取公司内部通讯录
	async contactList() {
		try {
			// 确保数据库已初始化
			await this.initSetup();

			// 判断是否登录
			let userId = this._userId;
			if (!userId) {
				return this.createError('请先登录');
			}

			console.log('[DEBUG] 当前登录用户ID:', userId);

			// 使用 UserModel 获取所有用户数据
			let list = await UserModel.getAllBig({
				USER_STATUS: 1  // 只获取状态为1的用户
			});

			console.log('[DEBUG] 数据库查询条件:', JSON.stringify({USER_STATUS: 1}));
			console.log('[DEBUG] 原始数据库查询结果数量:', list ? list.length : 0);
			if (list && list.length > 0) {
				console.log('[DEBUG] 第一条用户数据示例:', JSON.stringify(list[0]));
			}

			// 如果列表为空，返回空数组
			if (!list || list.length === 0) {
				console.log('[DEBUG] 数据库中没有找到有效用户数据');
				return this.createSuccess([]);
			}

			// 按部门分组
			let deptMap = {};
			for (let user of list) {
				let dept = user.USER_DEPT || '未分配';
				if (!deptMap[dept]) {
					deptMap[dept] = {
						dept: dept,
						users: []
					};
				}

				// 从USER_OBJ中获取额外信息
				let userObj = {};
				try {
					userObj = user.USER_OBJ ? (typeof user.USER_OBJ === 'string' ? JSON.parse(user.USER_OBJ) : user.USER_OBJ) : {};
				} catch (e) {
					console.error('[DEBUG] 解析USER_OBJ失败:', e);
					userObj = {};
				}

				console.log('[DEBUG] 处理用户数据:', {
					id: user._id,
					name: user.USER_NAME,
					dept: dept,
					userObj: userObj
				});

				// 添加用户信息，确保所有字段都有默认值
				deptMap[dept].users.push({
					id: user._id || '',
					name: user.USER_NAME || '未命名',
					mobile: user.USER_MOBILE || '',
					email: user.USER_EMAIL || '',
					dept: dept,
					position: userObj.zhiwu || '', // 使用USER_OBJ中的职位信息
					no: userObj.no || user.USER_ID || '', // 优先使用USER_OBJ中的工号
					avatar: user.USER_PIC || '/projects/oa/images/icon/empty.png',
					status: user.USER_STATUS || 0
				});
			}

			// 转换为数组格式并在内存中排序
			let result = Object.values(deptMap)
				.sort((a, b) => a.dept.localeCompare(b.dept, 'zh-CN'));

			// 对每个部门内的用户按姓名排序
			result.forEach(dept => {
				dept.users.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
			});

			console.log('[DEBUG] 最终处理结果 - 部门数量:', result.length);
			result.forEach(dept => {
				console.log('[DEBUG] 部门:', dept.dept, '用户数量:', dept.users.length);
			});

			return this.createSuccess(result);

		} catch (err) {
			console.error('[严重错误] 联系人列表获取失败:', err);
			console.error('[错误详情]', err.message);
			console.error('[错误堆栈]', err.stack);
			return this.createError('获取通讯录失败，请检查后台日志');
		}
	}

	// 获取动态类型文本
	_getTypeText(type) {
		const typeMap = {
			'project': '项目',
			'task': '任务',
			'approval': '审批'
		};
		return typeMap[type] || '';
	}

	/**
	 * 获取部门列表
	 */
	async deptList() {
		try {
			// 示例部门数据
			const departments = [
				{ id: 1, name: '总经办' },
				{ id: 2, name: '人力资源部' },
				{ id: 3, name: '财务部' },
				{ id: 4, name: '市场部' },
				{ id: 5, name: '研发部' },
				{ id: 6, name: '运营部' },
				{ id: 7, name: '销售部' },
				{ id: 8, name: '客服部' }
			];
			return this.createSuccess(departments);
		} catch (err) {
			console.error('获取部门列表失败：', err);
			return this.createError('获取部门列表失败');
		}
	}
}

module.exports = HomeController;